/**
 * 功能说明:
 * 功能作者:
 * 创建日期:
 * 版权归属:每特教育|蚂蚁课堂所有 www.itmayiedu.com
 */
package com.yxm.springbootsecurity.controller;

import com.yxm.springbootsecurity.Serializable.EvilSerialize;
import com.yxm.springbootsecurity.entity.Entity;
import com.yxm.springbootsecurity.entity.Evil;
import com.yxm.springbootsecurity.entity.FilePath;
import com.yxm.springbootsecurity.service.UserService;
import com.yxm.springbootsecurity.vo.ResponseDto;
import com.yxm.springbootsecurity.xxe.Xxe;
import com.yxm.springbootsecurity.entity.UserEntity;
import com.yxm.springbootsecurity.mapper.UserMapper;
import com.yxm.springbootsecurity.utils.TokenUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.xml.sax.InputSource;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private Xxe xxe;
	@Autowired
	private UserService userService;

	@Autowired
	private EvilSerialize evilSerialize;
	@RequestMapping("/login")
	public ResponseDto login(UserEntity userEntity) {
		System.out.println("账号密码信息:userEntity:" + userEntity.toString());
		return ResponseDto.successData(userService.login(userEntity.getUserName(), userEntity.getPassword()));
	}
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public ResponseDto login(HttpServletRequest request, HttpServletResponse response, @RequestBody UserEntity userEntity) throws IOException {
		System.out.println("账号密码信息:userEntity:" + userEntity.toString());
		List<UserEntity> UserEntitys=userService.login(userEntity.getUserName(), userEntity.getPassword());
		if (UserEntitys.size()>0){
			Cookie cookie=new Cookie("user",userEntity.getUserName());
			cookie.setMaxAge(60*5);
			cookie.isHttpOnly();
			cookie.setPath("/");
			response.addCookie(cookie);
			return ResponseDto.successData(UserEntitys);
		}else{
			return ResponseDto.errorMessage("账号或密码错误");
		}


	}
	@RequestMapping(value = "/account", method = RequestMethod.POST)
	public ResponseDto account(HttpServletRequest request, HttpServletResponse response, @RequestBody UserEntity userEntity) throws IOException {
		System.out.println("账号密码信息:userEntity:" + userEntity.toString());
		Cookie[] cookies=request.getCookies();
		for (Cookie cookie:cookies){
			if ("user".equals(cookie.getName())){
				if("admin".equals(cookie.getValue())){
					return ResponseDto.successData(userService.account(userEntity.getAccount()));
				}
			}

		}
		return ResponseDto.errorMessage("权限不足");

	}

	@RequestMapping(value = "/xxeIndex", method = RequestMethod.POST)
	public String xxeIndex(HttpServletRequest request,HttpServletResponse response,@RequestBody Entity entity) {
		String xml=entity.getXxeValue();
		Map retMap = new HashMap();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			Document doc =  sb.build(source);
			Element root = (Element) doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.valueOf(retMap);
	}

	@RequestMapping(value = "/securityConfig", method = RequestMethod.POST)
	public ResponseDto securityConfig(HttpServletRequest request, HttpServletResponse response, @RequestBody UserEntity userEntity) throws IOException {
		System.out.println("账号密码信息:userEntity:" + userEntity.toString());
		return ResponseDto.successData(userService.security(userEntity.getAccount()));

	}

	@RequestMapping(value = "/serialize", method = RequestMethod.POST)
	public ResponseDto Serialize(HttpServletRequest request, HttpServletResponse response, @RequestBody Evil evil) throws Exception {
		System.out.println("反序列化名:userEntity:" + evil.toString());
		byte[] bytes = evilSerialize.serializeToBytes(evil);
		// 反序列化
		Evil o = (Evil)evilSerialize.deserializeFromBytes(bytes);
		return ResponseDto.successData(o);

	}

	@RequestMapping(value = "/downFile", method = RequestMethod.POST)
	public ResponseDto downFile(HttpServletRequest request, HttpServletResponse response, @RequestBody FilePath filePath) throws Exception {
		System.out.println(this.getClass().getClassLoader().getResource("").getPath().replaceAll("springboot-security-0.0.1-SNAPSHOT.war!/WEB-INF/classes!/",""));
		//String path = request.getSession().getServletContext().getResource("/").getPath() +filePath.getPath();
		//linux运行执行下面的
		String path = this.getClass().getClassLoader().getResource("").getPath().replaceAll("file:","").
				replaceAll("springboot-security-0.0.1-SNAPSHOT.war!/WEB-INF/classes!/","")+filePath.getPath();

		//System.out.println(request.getSession().getServletContext().getRealPath("/"));
//		String path = request.getSession().getServletContext().getRealPath("/") +filePath.getPath();
//		System.out.println(this.getClass().getResource("/").getPath());
//		System.out.println(this.getClass().getResource("").getPath());



		System.out.println("下载路径为:" + path);
		String filename = path.substring(path.lastIndexOf("\\") +1);
		response.setHeader("content-disposition", "attachment; fileName=" + URLEncoder.encode(filename,"UTF-8"));

		FileInputStream fileInputStream = new FileInputStream(path);
		ServletOutputStream servletOutputStream = response.getOutputStream();

		byte[] bytes = new byte[1024];
		int iReadSize;
		while((iReadSize = fileInputStream.read(bytes)) != -1){
			servletOutputStream.write(bytes, 0, iReadSize);
		}

		fileInputStream.close();
		servletOutputStream.close();
		return ResponseDto.successData(servletOutputStream);

	}

	@GetMapping("/xxeTest")
	public String xxeTest(File file) throws JAXBException, IOException, XMLStreamException {

		return xxe.xmlExternalEntity(file);
	}

	@GetMapping("/getToken")
	public String getToken(){
		return TokenUtils.getToken();
	}

}
